package 实验六;

/**
 * 饿汉式
 */
class EagerInitializedSingleton {
    // 在类加载时即创建实例
    private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();

    // 私有构造函数防止实例化
    private EagerInitializedSingleton() {
    }

    // 提供全局访问点
    public static EagerInitializedSingleton getInstance() {
        return instance;
    }

    // 示例方法
    public void showMessage() {
        System.out.println("我是 饿汉式");
    }
}

/**
 * 懒汉式
 */
class LazyInitializedSingleton {
    private static LazyInitializedSingleton instance;

    private LazyInitializedSingleton() {
    }

    // 线程不安全
    // 第一次调用 getInstance 方法时才创建实例
    public static LazyInitializedSingleton getInstance() {
        if (instance == null) {
            instance = new LazyInitializedSingleton();
        }
        return instance;
    }

    public void showMessage() {
        System.out.println("我是懒汉式");
    }
}


public class 单例模式 {
    public static void main(String[] args) {
        EagerInitializedSingleton instance1 = EagerInitializedSingleton.getInstance();
        LazyInitializedSingleton instance2 = LazyInitializedSingleton.getInstance();
    }
}
